<template>
  <div id="main">
    <h2>班级管理</h2>
    <div class="head">
      <el-button
        type="primary"
        style="margin:20px"
        @click="handleOpen('添加班级', 1)"
      >添加班级</el-button>
      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="className"
          label="班级名称"
        />

        <el-table-column
          align="center"
          prop="classTeacher"
          label="授课教师"
        />

        <el-table-column
          align="center"
          prop="classLesson"
          label="课程名称"
        />
        <!-- <el-table-column
          align="center"
          prop="classType"
          label="班级类型"
        /> -->

        <el-table-column
          align="center"
          prop="classStartTime"
          :formatter="dateFormat"
          label="班级开始时间"
        />
        <el-table-column
          align="center"
          prop="classEndTime"
          :formatter="dateFormat"
          label="班级结束时间"
        />
        <!-- <el-table-column
          align="center"
          prop="classroomName"
          label="地点"
        /> -->
        <el-table-column
          id="classStatus"
          align="center"
          prop="classStatus"
          label="课程状态"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.classStatus=='未开始'">
              <p style="color: red;font-weight: 800;">未开始</p>
            </span>
            <span v-if="scope.row.classStatus=='进行中'">
              <p style="color:  rgb(30, 184, 30); ">进行中</p>
            </span>
            <span v-if="scope.row.classStatus=='已结束'">
              <p style="color: #a9aaaa;">已结束</p>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          id="button"
          align="center"
          label="操作"
          width="400px"
        >
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改班级', 2, Scope.row.classId)"
            >编辑/查看</el-button>
            <!-- <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.classId)">删除</el-button> -->
            <!-- <el-button type="primary" icon="el-icon-edit" @click="createVueqr(Scope.row.classId,Scope.row.classCompletionTimes)">生成二维吗</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- -------------------------------------列表展示区-------------------------------------------------------------------- -->

    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="clazz"
        :model="clazz"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="className"
          label="班级名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.className"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classPrincipalTeacherId"
          label="责任老师姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classPrincipalTeacherId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff3"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classTeacherId"
          label="授课老师姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classTeacherId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff4"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classMedicalDirectorId"
          label="医疗主管姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classMedicalDirectorId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff5"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classTeachingSupervisorId"
          label="教学主管姓名"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classTeachingSupervisorId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff2"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classLessonId"
          label="课程名称"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classLessonId"
            placeholder="请选择"
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="j in lesson"
              :key="j.lessonId"
              :value="j.lessonId"
              :label="j.lessonName"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classCompletionTimes"
          label="上课次数"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.classCompletionTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classType"
          label="班级类型"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classType"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option
              v-for="item in classType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="班级开始时间"
          :label-width="formLabelWidth"
          prop="classStartTime"
        >
          <el-date-picker
            v-model="clazz.classStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          label="班级计划完成时间"
          :label-width="formLabelWidth"
          prop="classEndTime"
        >
          <el-date-picker
            v-model="clazz.classEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          prop="classTimes"
          label="课时数量"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="clazz.classTimes"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item
          label="选择学生"
          :label-width="formLabelWidth"
          prop="studentId"
        >
          <el-select
            v-model="clazz.studentId"
            multiple
            placeholder="请选择"
            filterable=""
            style="width: 100%;"
          >
            <el-option
              v-for="j in student"
              :key="j.studentId"
              :value="j.studentId"
              :label="j.String"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="classStatus"
          label="课程状态"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classStatus"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option
              v-for="item in classStatus"
              :id="item.id"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="classTrainingMethods"
          label="训练方式"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="clazz.classTrainingMethods"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option
              v-for="item in classTrainingMethods"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        id="button"
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleClose"
        >取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('clazz')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddClass('clazz')"
        >添 加</el-button>
      </div>
    </el-dialog>
    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
    <el-dialog
      :visible.sync="qrVisible"
      title="二维码"
      width="240px"
      top="200px"
    >
      <div style="text-align:center">
        <vue-qr
          ref="qr"
          :text="text"
          :size="200"
        />
        <el-button
          type="primary"
          size="small"
          @click="downloadQR()"
        >下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addClass, deleteClass, updateClass, getAllClass, getClassById, ClassIdSearch, judgement, updateJudgement } from '@/api/class'
import { getAllJurisdiction } from '@/api/jurisdiction'
import { getStaffStringR, getStaffStringD, getStaffStringT, getStaffStringmedical } from '@/api/staff'
import { getAllLesson } from '@/api/lesson'
import { getAllStudentString } from '@/api/child'
import { isInteger } from '@/api/validata'
import moment from 'moment'
import VueQr from 'vue-qr'
export default {
  components: {
    VueQr
  },
  data () {
    return {
      readValue: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      studentId: '',
      // list: [],
      tableList: [],
      searchTableInfo: '',
      staff2: [],
      staff3: [],
      staff4: [],
      staff5: [],
      lesson: [],
      student: [],
      search: '',
      listLoading: false,
      dialogFormVisible: false,
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      clazz: {},
      clazzType: {},
      text: '',
      qrVisible: false,
      newClass: {
        ClassId: '',
        className: '',
        classTeacher: '',
        classLesson: '',
        classStartTime: '',
        classEndTime: '',
        classStatus: '',
        classType: ''
      },
      formLabelWidth: '200px',
      classType: [{
        value: 0,
        label: '个训'
      }, {
        value: 1,
        label: '合训'
      }, {
        value: 2,
        label: '集体'
      }],
      classStatus: [{
        id: 'start',
        value: 0,
        label: '未开始'
      }, {
        id: 'doing',
        value: 1,
        label: '进行中'
      }, {
        id: 'end',
        value: 2,
        label: '已结束'
      }],
      classTrainingMethods: [{
        value: 0,
        label: '工作时间'
      }, {
        value: 1,
        label: '非工作时间'
      }, {
        value: 2,
        label: '持续混合'
      }, {
        value: 3,
        label: '不定期'
      }],
      rules: {
        classCompletionTimes: [
          { required: true, message: '上课次数不能为空', trigger: 'blur' }
        ],
        lessonName: [
          { required: true, message: '课程不能为空', trigger: 'blur' }
        ],
        classMedicalDirectorId: [
          { required: true, message: '医疗主管不能为空', trigger: ['blur', 'change'] }
        ],
        classPrincipalTeacherId: [
          { required: true, message: '责任老师不能为空', trigger: ['blur', 'change'] }
        ],
        classStatus: [
          { required: true, message: '课程状态不能为空', trigger: ['blur', 'change'] }
        ],
        classTeacherId: [
          { required: true, message: '授课老师不能为空', trigger: ['blur', 'change'] }
        ],
        classTeachingSupervisorId: [
          { required: true, message: '教学主管不能为空', trigger: ['blur', 'change'] }
        ],
        classTimes: [
          { required: true, message: '课时数量不能为空', trigger: 'blur' },
          { validator: isInteger, trigger: ['blur', 'change'] }
        ],
        classType: [
          { required: true, message: '班级类型不能为空', trigger: ['blur', 'change'] }
        ],
        studentId: [
          { required: true, message: '学生不能为空', trigger: ['blur', 'change'] }
        ],
        className: [
          { required: true, validator: this.checkName, trigger: 'blur' }
        ],
        classLessonId: [{ required: true, message: '课程名称不能为空', trigger: ['blur', 'change'] }],
        classTrainingMethods: [{ required: true, message: '训练方式不能为空', trigger: ['blur', 'change'] }],
        classStartTime: [{ required: true, message: '班级开始时间不能为空', trigger: 'blur' }],
        classEndTime: [{ required: true, message: '班级计划完成时间不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list () {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created () {
    this.fetchData()
    this.getAllJurisdiction()
    this.getAllStaffTeachingDirector()
    this.getAllStaffResponsibleTeacher()
    this.getAllStaffTeacher()
    this.getAllStaffMedicalDirectorr()
    this.getAllLesson()
    this.getAllStudent()
  },
  methods: {
    // 时间格式化
    dateFormat (row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    // 时间格式化

    // 每页下拉显示数据
    handleSizeChange: function (size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleClick (row) {
      console.log(row)
    },
    getAllStaffTeachingDirector () {
      getStaffStringD().then(res => {
        console.log(res)
        this.staff2 = res.data.records
      })
    },
    getAllStaffResponsibleTeacher () {
      getStaffStringR().then(res => {
        console.log(res)
        this.staff3 = res.data.records
      })
    },

    getAllStaffTeacher () {
      getStaffStringT().then(res => {
        console.log(res)
        this.staff4 = res.data.records
      })
    },
    getAllStaffMedicalDirectorr () {
      getStaffStringmedical().then(res => {
        console.log(res)
        this.staff5 = res.data.records
      })
    },
    getAllLesson () {
      getAllLesson().then(res => {
        console.log(res)
        this.lesson = res.data
      })
    },
    getAllStudent () {
      getAllStudentString().then(res => {
        this.student = res.data.records
      })
    },
    fetchData () {
      this.tableList = []
      this.listLoading = true
      getAllClass().then(data => {
        console.log(data)
        for (var i = 0; i < data.data.records.length; i++) {
          this.newClass.classId = data.data.records[i].classId
          this.newClass.className = data.data.records[i].className
          this.newClass.classTeacher = data.data.records[i].classTeacherName
          this.newClass.classLesson = data.data.records[i].className
          this.newClass.classStartTime = data.data.records[i].classStartTime
          this.newClass.classEndTime = data.data.records[i].classEndTime
          // this.newClass.classroomName = data.obj[i].classroomName
          this.newClass.classStatus = data.data.records[i].classStatus
          this.newClass.classCompletionTimes = data.data.records[i].classCompletionTimes
          if (data.data.records[i].classType === 0) {
            this.newClass.classType = '普通班级'
          }
          if (data.data.records[i].classType === 1) {
            this.newClass.classType = '特殊班级'
          }
          if (data.data.records[i].classStatus === 0) {
            this.newClass.classStatus = '未开始'
          }
          if (data.data.records[i].classStatus === 1) {
            this.newClass.classStatus = '进行中'
          }
          if (data.data.records[i].classStatus === 2) {
            this.newClass.classStatus = '已结束'
          }
          this.tableList.push(this.newClass)
          this.newClass = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },

    handleDelete (id) {
      this.$confirm('确认删除该班级？').then(() =>
        deleteClass(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },

    handleAddClass (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const sss = []
          for (var i = 0; i < this.clazz.studentId.length; i++) {
            sss.push(this.clazz.studentId[i])
          }
          this.clazz.classStudentIDs = sss
          console.log(this.clazz)
          addClass(this.clazz).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.clazz = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen (title, type, id) {
      this.clazz = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getClassById(id).then(resp => {
          console.log('resp的数据：', resp)
          this.clazz = resp.data.records
          // var list = this.clazz.studentId.split(';')
          // list.length -= 1
          // for (var i = 0; i < list.length; i++) {
          //   list[i] = parseInt(list[i])
          // }
          // console.log(list)
          this.clazz.studentId = resp.data.records.classStudentIDNames
        })
      }
    },
    handleClose () {
      this.dialogFormVisible = false
      this.clazz = {}
    },
    handleUpdate (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.studentId = ''
          for (var i = 0; i < this.clazz.studentId.length; i++) {
            this.studentId += this.clazz.studentId[i] + ';'
          }
          this.clazz.studentId = this.studentId
          updateClass(this.clazz).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    ClassQuery () {
      ClassIdSearch(this.search).then(resp => {
        this.list = resp.obj
        this.currentPage = 1
      })
    },

    getAllJurisdiction () {
      getAllJurisdiction().then(resp => {
        console.log(resp)
        this.jurisdiction = resp.data[0]
      })
    },
    createVueqr (id, times) {
      this.text = id + ';' + times
      this.qrVisible = true
    },
    downloadQR () {
      const a = document.createElement('a')
      // 下载图名字
      a.download = '二维码'
      // url
      a.href = this.$refs.qr.$el.src
      // 合成函数，执行下载
      a.dispatchEvent(new MouseEvent('click'))
    },
    checkName (rule, value, callback) {
      if (this.editType === 1) {
        if (!value) {
          return callback(new Error('班级名称不能为空'))
        } else {
          judgement(this.clazz.className).then((resp) => {
            if (resp.data === '该班级名称已存在！') {
              return callback(new Error('该班级名称已存在！'))
            }
            if (resp.data === '该班级名称可用！') {
              callback()
            }
          })
        }
      } else if (this.editType === 2) {
        if (!value) {
          return callback(new Error('班级名称不能为空'))
        } else {
          updateJudgement(this.clazz.classId, this.clazz.className).then((resp) => {
            if (resp.msg === '该班级名称已存在！') {
              return callback(new Error('该班级名称已存在！'))
            }
            if (resp.msg === '该班级名称可用！') {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
#start {
  color: red;
}
#doing {
  color: rgb(30, 184, 30);
}
#end {
  color: #a9aaaa;
}
</style>
